﻿using System.Net.Mail;
using System.Text;

namespace Common
{
    /// <summary>
    /// Email操作帮助类
    /// </summary>
    public class EMailHelper
    {
        /// <summary>
        /// 邮件服务器地址
        /// </summary>
        public static string EmailServer { get; set; }
        /// <summary>
        /// 用户名
        /// </summary>
        public static string EmailUserName { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public static string EmailPassword { get; set; }
        /// <summary>
        /// 邮箱地址（发送者）
        /// </summary>
        public static string EmailAddress { get; set; }
        /// <summary>
        /// 名称
        /// </summary>
        public static string EmailName { get; set; }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="to">收件人邮箱地址</param>
        /// <param name="subject">主题</param>
        /// <param name="body">内容</param>
        /// <param name="encoding">编码</param>
        /// <param name="isBodyHtml">是否Html</param>
        /// <param name="enableSsl">是否SSL加密连接</param>
        /// <returns>是否成功</returns>
        public static void Send(string to, string subject, string body, bool isBodyHtml = true, bool enableSsl = false, string encoding = "UTF-8")
        {
            MailMessage message = new MailMessage();
            // 接收人邮箱地址
            message.To.Add(new MailAddress(to));
            message.From = new MailAddress(EmailAddress, EmailName);
            message.BodyEncoding = Encoding.GetEncoding(encoding);
            message.Body = body;
            //GB2312
            message.SubjectEncoding = Encoding.GetEncoding(encoding);
            message.Subject = subject;
            message.IsBodyHtml = isBodyHtml;

            SmtpClient smtpclient = new SmtpClient(EmailServer, 25);
            //SSL连接
            smtpclient.EnableSsl = enableSsl;
            smtpclient.UseDefaultCredentials = false;
            smtpclient.Credentials = new System.Net.NetworkCredential(EmailUserName, EmailPassword);
            //发送
            smtpclient.Send(message);
        }
    }
}